package com.gamota.mobi.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.devspark.appmsg.AppMsg;
import com.gamota.mobi.R;
import com.gamota.mobi.SettingsActivity;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.download.DownloadManager;
import com.gamota.mobi.download.DownloadManager.Request;
import com.gamota.mobi.download.DownloadService;
import com.gamota.mobi.event.Event;
import com.gamota.mobi.event.Event.BuyFailEvent;
import com.gamota.mobi.event.Event.BuySuccessEvent;
import com.gamota.mobi.event.Event.GetDownloadLinkSuccess;
import com.gamota.mobi.model.DownloadLink;
import com.gamota.mobi.model.DownloadedItem;
import com.gamota.mobi.network.DeleteFileTask;
import com.gamota.mobi.network.IDeleteFileListener;
import com.gamota.mobi.network.InstallBackgroundTask;
import com.gamota.mobi.network.ProgressDialogManager;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.StorageUtils;
import com.gamota.mobi.util.Utils;
import com.gamota.mobi.view.AlertDialogManager;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

@SuppressLint("NewApi")
public class DownloadedFragment extends BaseFragment implements OnClickListener, IDeleteFileListener, OnItemClickListener {
	
	private String downloadedType;
	private Resources res;
	private boolean inited = false;
	private AQuery aq;
	private boolean[] checkBoxState;
	private DownloadedAdapter adapter;
	private List<DownloadedItem> itemList;
	private ViewGroup actionMenuView;
	private ImageButton btnMenuSelectAll;
	private ImageButton btnMenuDelete;
	private ImageButton btnCloseActionMenu;
	private int count = 0;
	private BackgroundTasks bgTask;
	private String slug;
	private ProgressDialog pDialog;
	private DownloadManager downloadManager;
	private ListView listView;

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		downloadedType = getArguments().getString(Constants.DOWNLOADED_TYPE);
		res = getResources();
		itemList = new ArrayList<DownloadedItem>();
		adapter = new DownloadedAdapter(mContext, R.layout.downloaded_item, itemList);
		bgTask = new BackgroundTasks(mContext);
		downloadManager = new DownloadManager(mContext.getContentResolver(), mContext.getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(getActivity(), DownloadService.class);
		getActivity().startService(intent);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mParent = inflater.inflate(R.layout.layout_downloaded_list, null);
		listView = (ListView) mParent.findViewById(R.id.downloaded_files_list);
		actionMenuView = (ViewGroup) mParent.findViewById(R.id.action_menu);
		btnMenuSelectAll = (ImageButton) actionMenuView.findViewById(R.id.deselect_all);
		btnMenuDelete = (ImageButton) actionMenuView.findViewById(R.id.selection_delete);
		btnCloseActionMenu = (ImageButton) actionMenuView.findViewById(R.id.close_action_menu);
		btnMenuSelectAll.setOnClickListener(this);
		btnMenuDelete.setOnClickListener(this);
		btnCloseActionMenu.setOnClickListener(this);
		aq = new AQuery(mParent);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
		return mParent;
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		if(downloadedType.equalsIgnoreCase(res.getString(R.string.apps_downloaded))){
			loadData(downloadedType);
		}
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		EventBus.getDefault().register(this);
	}

	public void init() {
		if (inited) {
			return;
		}
		inited = true;
		loadData(downloadedType);
	}
	
	private void loadData(final String downloadedType){
		AsyncExecutor.create().execute(new RunnableEx() {
			@Override
			public void run() throws Exception {
				// TODO Auto-generated method stub
				DownloadedItem item;
				File dir = null;
				String suffix = "";
				List<DownloadedItem> list = new ArrayList<DownloadedItem>();
				if(downloadedType.equalsIgnoreCase(res.getString(R.string.apps_downloaded))){
					dir = new File(StorageUtils.APPS_ROOT);
					suffix = "apk";
				} else if(downloadedType.equalsIgnoreCase(res.getString(R.string.books_downloaded))){
					dir = new File(StorageUtils.EBOOK_ROOT);
					suffix = "epub";
				} else if(downloadedType.equalsIgnoreCase(res.getString(R.string.comics_downloaded))){
					dir = new File(StorageUtils.COMIC_ROOT);
					suffix = "zip";
				} else if(downloadedType.equalsIgnoreCase(res.getString(R.string.movies_downloaded))){
					dir = new File(StorageUtils.MOVIES_ROOT);
					suffix = "mp4";
				} else if(downloadedType.equalsIgnoreCase(res.getString(R.string.backuped))){
					dir = new File(StorageUtils.BACKUP_ROOT);
					suffix = "apk";
				}
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File[] files = dir.listFiles();
				if (files.length > 0) {
					Bitmap apkIcon = null;
					for (int i = 0; i < files.length; i++) {
						if (files[i].getName().endsWith(suffix)) {
							if(suffix.equalsIgnoreCase("apk")){
								PackageInfo packageInfo = mContext.getPackageManager().getPackageArchiveInfo(files[i].getAbsolutePath(),PackageManager.GET_ACTIVITIES);
								if (packageInfo != null) {
									ApplicationInfo appInfo = packageInfo.applicationInfo;
									if (Build.VERSION.SDK_INT >= 8) {
										appInfo.sourceDir = files[i].getAbsolutePath();
										appInfo.publicSourceDir = files[i].getAbsolutePath();
									}
									Drawable icon = appInfo.loadIcon(mContext.getPackageManager());
									apkIcon = ((BitmapDrawable) icon).getBitmap();
									item = new DownloadedItem(files[i].getName(), apkIcon, res.getString(R.string.apps_downloaded));
									item.setPath(files[i].getAbsolutePath());
									item.setSize(files[i].length());
									list.add(item);
								}
							} else if(suffix.equalsIgnoreCase("epub")){
								item = new DownloadedItem(files[i].getName(), null, res.getString(R.string.books_downloaded));
								item.setPath(files[i].getAbsolutePath());
								item.setSize(files[i].length());
								item.setImageResId(R.drawable.ic_launcher);
								list.add(item);
							} else if(suffix.equalsIgnoreCase("zip") && downloadedType.equalsIgnoreCase(res.getString(R.string.comics_downloaded))){
								item = new DownloadedItem(files[i].getName(), null, res.getString(R.string.comics_downloaded));
								item.setPath(files[i].getAbsolutePath());
								item.setSize(files[i].length());
								item.setImageResId(R.drawable.ic_launcher);
								list.add(item);
							} else if(suffix.equalsIgnoreCase("zip") && downloadedType.equalsIgnoreCase(res.getString(R.string.data_downloaded))){
								item = new DownloadedItem(files[i].getName(), null, res.getString(R.string.data_downloaded));
								item.setPath(files[i].getAbsolutePath());
								item.setSize(files[i].length());
								item.setImageResId(R.drawable.ic_zip);
								list.add(item);
							} else if(downloadedType.equalsIgnoreCase(res.getString(R.string.movies_downloaded))){
								item = new DownloadedItem(files[i].getName(), null, res.getString(R.string.movies_downloaded));
								item.setPath(files[i].getAbsolutePath());
								item.setSize(files[i].length());
								item.setImageResId(R.drawable.ic_launcher);
								list.add(item);
							}
						}
					}
					EventBus.getDefault().post(new Event.DownloadedFileLoadedEvent(list, downloadedType));
				} else {
					Thread.sleep(2000);
					EventBus.getDefault().post(new Event.EmptyFileEvent(downloadedType));
				}
			}
		});
	}
	
	public void onEventMainThread(Event.DownloadedFileLoadedEvent event){
		if(event.getType().equalsIgnoreCase(downloadedType)){
			aq.id(R.id.progress).gone();
			aq.id(R.id.empty_view).gone();
			aq.id(R.id.downloaded_files_list).visible();
			checkBoxState = new boolean[event.getList().size()*2];
			for(DownloadedItem item : event.getList()){
				itemList.add(item);
			}
			adapter.notifyDataSetChanged();
		}
	}
	
	public void onEventMainThread(Event.EmptyFileEvent event){
		if(event.getType().equalsIgnoreCase(downloadedType)){
			aq.id(R.id.progress).gone();
			aq.id(R.id.empty_view).visible();
			aq.id(R.id.downloaded_files_list).gone();
		}
	}
	
	@SuppressLint("NewApi")
	private class DownloadedAdapter extends ArrayAdapter<DownloadedItem> {
		
		private AQuery aq;
		private Typeface robotoCondensed;
		private Typeface robotoBoldCondensed;

		public DownloadedAdapter(Context context, int resource, List<DownloadedItem> objects) {
			super(context, resource, objects);
			// TODO Auto-generated constructor stub
			robotoBoldCondensed = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_bold_condensed));
			robotoCondensed = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_condensed));
		}
		public void deleteItem(int pos){
			itemList.remove(pos);
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				convertView = LayoutInflater.from(mContext).inflate(R.layout.downloaded_item, null);
				holder = new ViewHolder();
				holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb_select_file);
				holder.btnQuickMenu = (ImageButton) convertView.findViewById(R.id.btn_quick_menu);
				holder.icon = (ImageView) convertView.findViewById(R.id.downloaded_icon);
				holder.name = (TextView) convertView.findViewById(R.id.downloaded_name);
				holder.size = (TextView) convertView.findViewById(R.id.downloaded_size);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final DownloadedItem item = getItem(position);
			if(item != null){
				aq = new AQuery(convertView);
				if(item.getIcon() != null){
					aq.id(holder.icon).image(item.getIcon());
				} else {
					aq.id(holder.icon).image(item.getImageResId());
				}
				aq.id(holder.name).text(item.getName()).typeface(robotoBoldCondensed);
				aq.id(holder.size).text(Utils.printSize(item.getSize())).typeface(robotoCondensed);
				aq.id(holder.checkBox).checked(checkBoxState[position]).clicked(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(((CheckBox)v).isChecked()){
			                   checkBoxState[position] = true;
			                   item.setCheck(true);
			                   if(actionMenuView.getVisibility() != View.VISIBLE){
									actionMenuView.setVisibility(View.VISIBLE);
									actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_appear));
			                   }
			                   count++;
			               } else{
			                   checkBoxState[position] = false;
			                   item.setCheck(false);
			                   count--;
			               }
			               if(count == 0){
			            	   if(actionMenuView.getVisibility() == View.VISIBLE){
			            		   actionMenuView.setVisibility(View.GONE);
			            		   actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_disappear));
			            	   }
			               }
					}
				});
				aq.id(holder.btnQuickMenu).clicked(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
							PopupMenu menu = new PopupMenu(mContext, v);
							menu.getMenuInflater().inflate(R.menu.downloaded_menu, menu.getMenu());
							menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
								@Override
								public boolean onMenuItemClick(MenuItem menuItem) {
									switch (menuItem.getItemId()) {
									case R.id.menu_open:
										if(item.getType().equalsIgnoreCase(res.getString(R.string.apps_downloaded))){
											Intent intent = new Intent(Intent.ACTION_VIEW);
											intent.setDataAndType(Uri.fromFile(new File(item.getPath())), "application/vnd.android.package-archive");
											intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
											intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
											intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
											startActivity(intent);
										} else if(item.getType().equalsIgnoreCase(res.getString(R.string.books_downloaded))||item.getType().equalsIgnoreCase(res.getString(R.string.comics_downloaded))){
											openReader(item.getPath(), item.getType());
										} else if(item.getType().equalsIgnoreCase(res.getString(R.string.movies_downloaded))){
//											Intent video = new Intent(getActivity(), VideoActivity.class);
//											video.putExtra(Constants.MOVIE_PATH, item.getPath());
//											video.putExtra(Constants.MOVIE_TITLE, item.getName());
//											video.putExtra(Constants.MOVIE_EPISODE, "");
//											startActivity(video);
										}
	 									break;
									case R.id.menu_delete:
										DeleteFileTask task = new DeleteFileTask(mContext, true);
										task.setDeleteFileListener(new IDeleteFileListener() {
											
											@Override
											public void onDeleteFileSuccess() {
												// TODO Auto-generated method stub
												adapter.remove(item);
												adapter.notifyDataSetChanged();
												count = 0;
												 if(actionMenuView.getVisibility() == View.VISIBLE){
								            		   actionMenuView.setVisibility(View.GONE);
								            		   actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_disappear));
								            	 }
												AppMsg.makeText(getActivity(), R.string.deleted, AppMsg.STYLE_INFO, null).show();
											}
											
											@Override
											public void onDeleteFileError() {
												AppMsg.makeText(getActivity(), R.string.delete_error, AppMsg.STYLE_ALERT, null).show();
											}
										});
										task.execute(item.getPath());
										break;
									}
									return true;
								}
							});
							menu.show();
						} else {
							main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
							popupMenuCompat.add(1, R.string.open);
							popupMenuCompat.add(2, R.string.delete);
							popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
								@Override
								public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
									switch (menuItem.getItemId()) {
									case 1:
										if(item.getType().equalsIgnoreCase(res.getString(R.string.apps_downloaded))){
											Intent intent = new Intent(Intent.ACTION_VIEW);
											intent.setDataAndType(Uri.fromFile(new File(item.getPath())), "application/vnd.android.package-archive");
											intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
											intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
											intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
											startActivity(intent);
										} else if(item.getType().equalsIgnoreCase(res.getString(R.string.books_downloaded))||item.getType().equalsIgnoreCase(res.getString(R.string.comics_downloaded))){
											openReader(item.getPath(), item.getType());
										}else if(item.getType().equalsIgnoreCase(res.getString(R.string.movies_downloaded))){
//											Intent video = new Intent(getActivity(), VideoActivity.class);
//											video.putExtra(Constants.MOVIE_PATH, item.getPath());
//											video.putExtra(Constants.MOVIE_TITLE, item.getName());
//											video.putExtra(Constants.MOVIE_EPISODE, "");
//											startActivity(video);
										}
										break;
									case 2:
										DeleteFileTask task = new DeleteFileTask(mContext, true);
										task.setDeleteFileListener(new IDeleteFileListener() {
											
											@Override
											public void onDeleteFileSuccess() {
												// TODO Auto-generated method stub
												adapter.remove(item);
												adapter.notifyDataSetChanged();
												count = 0;
												 if(actionMenuView.getVisibility() == View.VISIBLE){
								            		   actionMenuView.setVisibility(View.GONE);
								            		   actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_disappear));
								            	 }
												AppMsg.makeText(getActivity(), R.string.deleted, AppMsg.STYLE_INFO, null).show();
											}
											
											@Override
											public void onDeleteFileError() {
												AppMsg.makeText(getActivity(), R.string.delete_error, AppMsg.STYLE_ALERT, null).show();
											}
										});
										task.execute(item.getPath());
										break;
									}
								}
							});
							popupMenuCompat.show(v);
						}
					}
				});
			}
			return convertView;
		}
	}
	
	private static class ViewHolder {
		CheckBox checkBox;
		ImageView icon;
		TextView name;
		TextView size;
		ImageButton btnQuickMenu;
	}

	public void openReader(String path, String conten_type){
	    String mimetype = "";
	    if(conten_type.equalsIgnoreCase(res.getString(R.string.books_downloaded))){
	    	mimetype ="application/epub+zip";
	    }else if(conten_type.equalsIgnoreCase(res.getString(R.string.comics_downloaded))){
	    	mimetype ="application/x-acv";
		}
		if(Utils.checkReader(mContext, conten_type, path, mimetype)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(new File(path)), mimetype);
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			if(conten_type.equalsIgnoreCase(res.getString(R.string.books_downloaded))){
				String items[] = {"Cool Reader"};
				slug = "cooldreader";
				showDialogConfirmNoReader(R.string.no_ebook_reader, R.string.choose_book_reader_app, items, slug);
			}else if(conten_type.equalsIgnoreCase(res.getString(R.string.comics_downloaded))){
				String items[] = {"Droid Comic Viewer"};
				slug = Utils.ACV_SLUG;
				showDialogConfirmNoReader(R.string.no_comic_reader, R.string.choose_book_reader_app, items, slug);
			}
		}
	}
	
	private void showDialogConfirmNoReader(int title,final int content_msg,final String[] selector,final String slug){
		AlertDialogManager am = new AlertDialogManager(mContext);
		am.showDialog(title, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				AlertDialogManager am = new AlertDialogManager(mContext);
				am.showDialogWithItems(content_msg, selector, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface v, int pos) {
						// TODO Auto-generated method stub
						pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
						String accessToken = Utils.getStaticAccessToken(getActivity());
						BackgroundTasks bgTask = new BackgroundTasks(mContext);
						bgTask.buyContent(downloadedType, accessToken, slug, 0);
					}
				});
			}
		});
	}
	
//	private void openComic(String path){
//		if(Utils.checkDroidComicViewer(mContext, path)){
//			Intent intent = new Intent(Intent.ACTION_VIEW);
//			intent.setDataAndType(Uri.fromFile(new File(path)), "application/x-acv");
//			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//			startActivity(intent);
//		} else {
//			AlertDialogManager am = new AlertDialogManager(mContext);
//			am.showDialog(R.string.no_comic_reader, new DialogInterface.OnClickListener() {
//				@Override
//				public void onClick(DialogInterface arg0, int arg1) {
//					// TODO Auto-generated method stub
//					AlertDialogManager am = new AlertDialogManager(mContext);
//					String items[] = {"Droid Comic Viewer"};
//					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface v, int pos) {
//							// TODO Auto-generated method stub
//							pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
//							String accessToken = Utils.getStaticAccessToken(getActivity());
//							slug = Utils.ACV_SLUG;
//							bgTask.buyContent(downloadedType, accessToken, slug, 0);
//						}
//					});
//				}
//			});
//		}
//	}
	
	public void onEventMainThread(BuySuccessEvent event){
		if(event.getTopType().equalsIgnoreCase(downloadedType)){
			String accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getDownloadLink(downloadedType, accessToken, event.getSlug(), event.getVersionId(), Utils.getStaticIsRooted(getActivity()), "direct");
		}
	}
	
	public void onEventMainThread(BuyFailEvent event){
		if(event.getTopType().equalsIgnoreCase(downloadedType)){
			if(pDialog != null){
				pDialog.dismiss();
			}
			AppMsg.makeText(getActivity(), event.getMessage(), AppMsg.STYLE_ALERT, null).show();
		}
	}
	
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(event.getTopType().equalsIgnoreCase(downloadedType)){
			if(pDialog != null){
				pDialog.dismiss();
			}
			DownloadLink download = event.getDl();
			String url = download.getDownload();
			Uri srcUri = Uri.parse(url.replace(" ", "%20"));
			DownloadManager.Request request = new Request(srcUri);
			request.setTitle(slug);
			request.setDescription(slug);
			setDownloadData(request, url);
			downloadManager.enqueue(request);
		}
	}
	
	private void setDownloadData(Request request, String url){
		request.setWhere(downloadedType);
		request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
		request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.deselect_all:
			if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
				PopupMenu menu = new PopupMenu(mContext, v);
				menu.getMenuInflater().inflate(R.menu.select_all_menu, menu.getMenu());
				menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						// TODO Auto-generated method stub
						switch (item.getItemId()) {
						case R.id.menu_select_all:
							for(int i=0; i < itemList.size(); i++){
								checkBoxState[i] = true;
								itemList.get(i).setCheck(true);
							}
							count = checkBoxState.length;
							adapter.notifyDataSetChanged();
							break;

						case R.id.menu_deselect_all:
							for(int i=0; i < itemList.size(); i++){
								checkBoxState[i] = false;
								itemList.get(i).setCheck(false);
							}
							count = 0;
							if(actionMenuView.getVisibility() == View.VISIBLE){
			            		actionMenuView.setVisibility(View.GONE);
			            		actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_disappear));
			            	}
							adapter.notifyDataSetChanged();
							break;
						}
						return true;
					}
				});
				menu.show();
			} else {
				main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
				popupMenuCompat.add(1, R.string.select_all);
				popupMenuCompat.add(2, R.string.deselect_all);
				popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
						switch (menuItem.getItemId()) {
						case 1:
							for(int i=0; i < itemList.size(); i++){
								checkBoxState[i] = true;
								itemList.get(i).setCheck(true);
							}
							count = checkBoxState.length;
							adapter.notifyDataSetChanged();
							break;
						case 2:
							for(int i=0; i < itemList.size(); i++){
								checkBoxState[i] = false;
								itemList.get(i).setCheck(false);
							}
							count = 0;
							if(actionMenuView.getVisibility() == View.VISIBLE){
			            		actionMenuView.setVisibility(View.GONE);
			            		actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_disappear));
			            	}
							adapter.notifyDataSetChanged();
							break;
						}
					}
				});
				popupMenuCompat.show(v);
			}
			break;
			
		case R.id.selection_delete:
			AlertDialogManager am = new AlertDialogManager(mContext);
			am.showButtonsDialog(R.string.confirm_delete, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						List<String> paths = new ArrayList<String>();
						for(int i=0; i<itemList.size(); i++){
							if(itemList.get(i).isCheck() && checkBoxState[i] == true){
								paths.add(itemList.get(i).getPath());
							}
						}
						DeleteFileTask task = new DeleteFileTask(getActivity(), true);
						task.setDeleteFileListener(DownloadedFragment.this);
						task.execute(paths.toArray(new String[paths.size()]));
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			});
			break;
			
		case R.id.close_action_menu:
			for(int i=0; i < itemList.size(); i++){
				checkBoxState[i] = false;
				itemList.get(i).setCheck(false);
			}
			count = 0;
			if(actionMenuView.getVisibility() == View.VISIBLE){
        		actionMenuView.setVisibility(View.GONE);
        		actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_disappear));
        	}
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onDeleteFileSuccess() {
		// TODO Auto-generated method stub
		for(int i = itemList.size() - 1; i >= 0; i--){
			if(checkBoxState[i] == true){
				checkBoxState[i] = false;
				adapter.deleteItem(i);
			}
		}
		count = 0;
		adapter.notifyDataSetChanged();
		if(actionMenuView.getVisibility() == View.VISIBLE){
 		   actionMenuView.setVisibility(View.GONE);
 		   actionMenuView.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.footer_disappear));
		}
		AppMsg.makeText(getActivity(), R.string.deleted, AppMsg.STYLE_INFO, null).show();
		if(adapter.isEmpty()){
			aq.id(R.id.progress).gone();
			aq.id(R.id.empty_view).visible();
			aq.id(R.id.downloaded_files_list).gone();
		}
	}

	@Override
	public void onDeleteFileError() {
		// TODO Auto-generated method stub
		AppMsg.makeText(getActivity(), R.string.delete_error, AppMsg.STYLE_ALERT, null).show();
	}
	
	public void onEventMainThread(final Event.DownloadFailEvent e){
		if(e.getReferer().equalsIgnoreCase(downloadedType)){
			if(e.getMessage() != null){
				if(e.getMessage().contains("exist")){
					AlertDialogManager am = new AlertDialogManager(getActivity());
					am.showFileDowloadDialog("apps", R.string.install_already_exist_file, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
								boolean autoInstall = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SettingsActivity.KEY_AUTO_INSTALL, false);
					    		if(!autoInstall){
					    			Utils.installAPK(getActivity(), StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
					    		} else {
					    			InstallBackgroundTask task = new InstallBackgroundTask(getActivity());
					    			task.execute(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()), Utils.getFileName(e.getPath()));
					    		}
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								Utils.deleteFile(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
								break;
							case DialogInterface.BUTTON_NEUTRAL:
								dialog.dismiss();
								break; 
							}
						}
					});
				} else {
					AppMsg.makeText(getActivity(), e.getMessage(), AppMsg.STYLE_ALERT, null).show();
				}
			}
			downloadManager.remove(e.getId());
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		DownloadedItem item = (DownloadedItem) parent.getItemAtPosition(pos);
		if(item.getType().equalsIgnoreCase(getString(R.string.apps_downloaded))){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.fromFile(new File(item.getPath())), "application/vnd.android.package-archive");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else if(item.getType().equalsIgnoreCase(res.getString(R.string.books_downloaded))||item.getType().equalsIgnoreCase(res.getString(R.string.comics_downloaded))){
			openReader(item.getPath(), item.getType());
		}else {
//			Intent video = new Intent(getActivity(), VideoActivity.class);
//			video.putExtra(Constants.MOVIE_PATH, item.getPath());
//			video.putExtra(Constants.MOVIE_TITLE, item.getName());
//			video.putExtra(Constants.MOVIE_EPISODE, "");
//			startActivity(video);
		}
	}
}
